package com.wyd.studentboot.serviceImpl;

import com.wyd.studentboot.bean.Msg;
import com.wyd.studentboot.bean.SignInLag;
import com.wyd.studentboot.mapper.SignInLagMapper;
import com.wyd.studentboot.service.SignInLagService;
import com.wyd.studentboot.util.TimeTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SignInLagServiceImpl implements SignInLagService {
    @Autowired
    private SignInLagMapper dao;
    /**
     *时段签到(18:00-20:00)，lagCheck()方法中定义时间段
     * @param sign
     * @return 0签到时间段设置错误1未到签到时间2签到已结束3已签到4签到成功5签到失败
     */
    @Override
    public Msg add(SignInLag sign) {
        //检查是否已经签到
        List<SignInLag> list = dao.getStatus(sign.getStudent_id());
        System.out.println(list.size());
        if (list.size()!=0)
            return new Msg(3,"您今日已签到！无需再操作。");
        int end = lagCheck();
        //可签到
        if(end==3)end = dao.add(sign.getStudent_id(),sign.getStatus())!=0?4:5;
        Msg msg = new Msg();
        msg.setCode(end);
        if(end==1)msg.setMsg("抱歉，签到时间还未到！");
        else if(end==2)msg.setMsg("抱歉，签到时间已结束！");
        else if(end==4)msg.setMsg("恭喜，签到成功！");
        else msg.setMsg("抱歉，系统繁忙，签到失败！");
        return msg;
    }

    /**
     * 检查签到时间是否在时间段内
     * @return 0签到时间段设置错误1未到签到时间2签到已结束3可签到
     */
    private int lagCheck(){
        Date date = new Date();
        //获取当天开始、结束签到时间的时间戳
        long beginTime = TimeTools.timeToStamp(TimeTools.getDay()+" 18:00:00");
        long endTime = TimeTools.timeToStamp(TimeTools.getDay()+" 20:00:00");
        //获取当前时间和签到时间段的时间戳的差值
        long begin = TimeTools.timeLag(new Date(beginTime),date);
        long end = TimeTools.timeLag(new Date(endTime),date);
        if(beginTime>=endTime) return 0;
        if(begin<0) return 1;
        else if(end>0) return 2;
        else return 3;
    }
    @Override
    public List<SignInLag> history(String student_id) {
        return dao.findBystudent_Id(student_id);
    }
}
